package com.isunland.managesystem.ui;

import android.R.color;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.CompanyForumTopicListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CompanyForumTopic;
import com.isunland.managesystem.entity.CompanyForumTopic.actualObject;
import com.isunland.managesystem.entity.CompanyForumType;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 企业论坛发布列表
 *
 * @author wu
 */
public class KnowledgeForumPostListFragment extends BaseListFragment {

  public static final String EXTRA_FORUM_TYPE = "com.isunland.managesystem.ui.EXTRA_FORUM_TYPE";
  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.EXTRA_VALUE";

  public static final String EXTRA_TOPIC_QUERY = "com.isunland.managesystem.ui.EXTRA_TOPIC_QUERY";
  public static final String EXTRA_QUERY_TYPE = "com.isunland.managesystem.ui.EXTRA_QUERY_TYPE";

  private static final int REQUEST_ADD = 0;
  private static final int REQUEST_DELETE = 1;
  private static final int REQUEST_SELECT = 3;// 筛选
  private CompanyForumTopicListAdapter mAdapter;

  private int mPage = 1;// 请求第几页的数据.

  private String mBeginDate;// 查询话题的开始时间
  private String mEndDate;// 查询话题的结束时间
  private String mStaffid;// 查询话题的话题发布人的id
  private String mStaffName;
  private String mQuery;
  //private String mEditType;// 修改时话题类别
  private CompanyForumType mCompanyType;
  private CurrentUser mCurrentUser;

  public static KnowledgeForumPostListFragment newInstance(CompanyForumType type) {
    Bundle bundle = new Bundle();

    bundle.putSerializable(EXTRA_VALUE, type);

    KnowledgeForumPostListFragment fragment = new KnowledgeForumPostListFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      if (mActivity.getSupportActionBar() != null) {

        mActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      }
    }
    //mEditType = getArguments().getString(EXTRA_EDIT_TYPE);
    //mType = getArguments().getString(EXTRA_FORUM_TYPE);
    //myPublishTopic = getArguments().getString(EXTRA_MINE);
    mCompanyType = (CompanyForumType) getArguments().getSerializable(EXTRA_VALUE);
    if (mCompanyType != null && mCompanyType.getName() != null) {
      mActivity.getSupportActionBar().setTitle(mCompanyType.getName());
    }
    mCurrentUser = CurrentUser.newInstance(getActivity());
  }

  @Override protected String setEmptyText() {
    String message;
    if (EXTRA_TOPIC_QUERY.equals(mQuery)) {
      message = getResources().getString(R.string.thisStaffNoTopic);
    } else {
      message = getResources().getString(R.string.noTopicPublish);
    }
    return message;
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (EXTRA_TOPIC_QUERY.equals(mQuery)) {
      if (mActivity.getSupportActionBar() != null) {
        mActivity.getSupportActionBar().setTitle(R.string.topiclist);
      }
    }
    int padding = MyUtils.dip2px(getActivity().getApplicationContext(), 10);
    //noinspection deprecation
    mListview.setDivider(new ColorDrawable(getResources().getColor(color.transparent)));
    mListview.setDividerHeight(padding);
    mListview.setPadding(padding, 0, padding, padding);
    mPullRefreshListView.setMode(Mode.BOTH);
  }

  /**
   * 添加发布按钮
   */
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //除了"我发布的话题"列表意外都可发布新话题.
    if (mCompanyType != null && !mCompanyType.isPublisher()) {
      inflater.inflate(R.menu.menu_forum_publish, menu);
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public String getUrl() {
    return ApiConst.URL_KNOWLEDGEFORUM_POST_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    if (EXTRA_TOPIC_QUERY.equals(mQuery)) {
      //韦加不用发布人筛选.
      //if (mStaffid != null) {
      //    params.put("regStaffId", mStaffid);
      //}
      if (mBeginDate != null && mEndDate != null) {
        params.put("beginregDate", mBeginDate + " 00:00:00");
        params.put("endregDate", mEndDate + " 23:59:59");
      }
      if (mCompanyType != null && mCompanyType.getCustomAttrs() != null) {
        params.put("topicKindCode", mCompanyType.getCustomAttrs());
      }
    } else {
      if (mCompanyType != null && mCompanyType.isPublisher()) {
        params.put("regStaffId", mCurrentUser.getJobNumber());
      } else {
        if (mCompanyType != null && mCompanyType.getCustomAttrs() != null) {
          params.put("topicKindCode", mCompanyType.getCustomAttrs());
        }
        params.put("orderField", "discuss_Count DESC,REG_DATE");
        params.put("orderSeq", "DESC");
      }
    }
    params.put("page", mPage + "");
    params.put("rows", "20");
    return params;
  }

  @Override public void resolveResponse(String arg0) {
    CompanyForumTopic topicList = new Gson().fromJson(arg0, CompanyForumTopic.class);
    List<actualObject> forumTopicContent = topicList.getData();
    if (forumTopicContent != null && forumTopicContent.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
    }
    setAdapter(forumTopicContent);
  }

  private void setAdapter(List<actualObject> topicDetail) {
    if (topicDetail == null) {
      topicDetail = new ArrayList<>();
    }
    if (mAdapter == null) {
      mAdapter = new CompanyForumTopicListAdapter(getActivity(), topicDetail);
      setListAdapter(mAdapter);
      return;// 初始化时不需要向下执行.
    }
    if (mPage == 1) {
      mAdapter.clear();
    }

    mAdapter.addAll(topicDetail);
    ((CompanyForumTopicListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  /**
   * 跳转到话题回复列表
   */
  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    actualObject topicContent = mAdapter.getItem(position - 1);

    Intent intent = new Intent(getActivity(), KnowledgeForumPostDetailAcrivity.class);
    intent.putExtra(KnowledgeForumPostDetailFragment.EXTRA_VALUE, topicContent);
    startActivityForResult(intent, REQUEST_DELETE);

    super.onListItemClick(l, v, position, id);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
      /**
       * 响应返回按钮
       */
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      // 跳到发布话题页面
      case R.id.menu_item_publish:
        if (mCompanyType != null && mCompanyType.getCustomAttrs() != null) {
          intent = new Intent(getActivity(), KnowledgeForumTopicPublishActicity.class);
          intent.putExtra(EXTRA_FORUM_TYPE, mCompanyType);
          startActivityForResult(intent, REQUEST_ADD);
        }

        break;
      // 按照条件进行查询：按发布人户发布时间
      case R.id.menu_item_topic_search:
        intent = new Intent(getActivity(), KnowledgeforumTopicQueryActicity.class);
        intent.putExtra(KnowledgeforumTopicQueryFragment.REQUEST_STAFF_NAME, mStaffName);
        intent.putExtra(KnowledgeforumTopicQueryFragment.REQUEST_START_DATE, mBeginDate);
        intent.putExtra(KnowledgeforumTopicQueryFragment.REQUEST_END_DATE, mEndDate);
        startActivityForResult(intent, REQUEST_SELECT);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_SELECT) {
      mStaffid = data.getStringExtra(KnowledgeforumTopicQueryFragment.EXTRA_STAFF_ID);
      mBeginDate = data.getStringExtra(KnowledgeforumTopicQueryFragment.EXTRA_BEGIN_DATE);
      mEndDate = data.getStringExtra(KnowledgeforumTopicQueryFragment.EXTRA_END_DATE);
      mQuery = data.getStringExtra(EXTRA_QUERY_TYPE);
      mStaffName = data.getStringExtra(KnowledgeforumTopicQueryFragment.EXTRA_STAFF_NAME);
      LogUtil.i("mBeginDate------------" + mBeginDate);
      LogUtil.i("mStaffid----------" + mStaffid);
      LogUtil.i("mEndDate----------" + mEndDate);
      LogUtil.i("mQuery----------" + mQuery);
      LogUtil.i("mStaffName----------" + mStaffName);
      volleyPost();
      return;
    }

    // if(requestCode==REQUEST_TOPIC_EDIT||requestCode==REQUEST_TOPIC_FILE_EDIT){
    // volleyPost();
    // }
    mPullRefreshListView.setMode(Mode.PULL_FROM_START);
    mPage = 1;
    volleyPost();
    mPullRefreshListView.setMode(Mode.BOTH);

    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    Mode mode = refreshView.getCurrentMode();
    if (mode.equals(Mode.PULL_FROM_START)) {

      mPage = 1;
    }
    if (mode.equals(Mode.PULL_FROM_END)) {
      mPage++;
    }
    volleyPost();
  }
}
